<template>
  <view>
    <view v-if="listData.length > 0">
      <view class="cu-card-wrap" v-for="item in listData" :key="`${item.projectId}-${item.projectInfoId}`">
        <view class="title flex">
          <image class="icon-style" src="/static/images/icon1.png" mode="aspectFill"></image>
          {{ item.projectName }}
        </view>
        <view class="body-wrap">
          <view class="content-wrap">
            <view class="label">项目编号：</view>
            <view class="value">{{ item.projectCode }}</view>
          </view>
          <view class="content-wrap">
            <view class="label">项目类型：</view>
            <view class="value">{{ item.projectTypeLabel }}</view>
          </view>
          <view class="content-wrap">
            <view class="label">所属部门：</view>
            <view class="value">{{ item.deptName }}</view>
          </view>
          <view class="content-wrap">
            <view class="label">所属区域：</view>
            <view class="value">{{ item.areaName }}</view>
          </view>
          <view class="content-wrap">
            <view class="label">项目日期：</view>
            <view class="value">{{ item.projectDate }}</view>
          </view>
          <view class="content-wrap">
            <view class="label">项目进度：</view>
            <view class="value">{{ item.workProgressLabel }}</view>
          </view>
        </view>
        <view class="footer-wrap">
          <view class="button-wrap button-wrap-todo">
            <view class="button-wrap-left">
              <cu-dropdown v-if="isChangeUser(item)" style="z-index: 90">
                <template #dropdown>
                  <cu-dropdown-item v-if="isChangeUser(item)" @click="showUserSelect(item, 1)"
                    >更换监护人
                  </cu-dropdown-item>
                  <cu-dropdown-item v-if="isChangeUser(item)" @click="showUserSelect(item, 2)"
                    >更换项目负责人
                  </cu-dropdown-item>
                </template>
                <view class="more-button">更多</view>
              </cu-dropdown>
            </view>
            <view class="flex">
              <view v-if="item.directorFlag === 'Y'" class="button button-orange" @click="applyFor(item)">
                申请作业票
              </view>
              <view v-else class="button" @click="detail(item)"> 查看 </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view v-else>
      <Empty></Empty>
    </view>

    <!--筛选-->
    <CuFilterTicketApply ref="cuFilter" :showArr="filterShowArr" @submit="filterSubmit" />
    <!--转办单人-->
    <user-selector ref="transferSelectorRef" @change="transferSelectorChange" />
    <!-- 更换监护人、项目负责人 -->
    <cu-dept-user-select
      ref="deptUserSelectRef"
      @change="onDeptUserChange"
      :userRequestApi="deptUserSelectProps.userRequestApi"
      :with-count="deptUserSelectProps.withCount"
    ></cu-dept-user-select>
  </view>
</template>

<script>
import { turnDo, changeGuardian, changeProjectDuty, getTicketApplyList } from '../../../api/spw/ticketApply'

import Empty from '@/components/cu-empty/index.vue'
import { mapGetters } from 'vuex'
import UserSelector from '@/components/user-selector/index.vue'
import UserSelectorMultiple from '../ticket-info/UserSelectorMultiple.vue'
import CuDropdown from '@/components/cu-dropdown/index.vue'
import CuDropdownItem from '@/components/cu-dropdown/cu-dropdown-item.vue'
import CuFilterTicketApply from '@/components/cu-filter-ticket-apply/cu-filter.vue'
import store from '../../../store'
import CuDeptUserSelect from '@/components/cu-dept-user-select/cu-dept-user-select.vue'
import { queryProjectGuardian } from '@/api/spw/project'

export default {
  components: {
    CuDeptUserSelect,
    Empty,
    UserSelector,
    UserSelectorMultiple,
    CuDropdown,
    CuDropdownItem,
    CuFilterTicketApply
  },
  data() {
    return {
      deptUserSelectProps: {
        userRequestApi: null,
        withCount: true
      },
      listData: [],
      pageNum: 1,
      pageSize: 10,
      total: null,
      isFinished: false,
      filterShowArr: ['progress', 'range', 'selectUser'],
      searchParams: {
        directorId: this.$store.state.user.staffId
      },
      transferForm: {},
      type: 0,
      pName: 0,
      curUser: '',
      dataParam: {}
    }
  },
  computed: {
    ...mapGetters(['staffId'])
  },
  // 筛选按钮点击
  onNavigationBarButtonTap() {
    this.$refs.cuFilter.toggle()
  },

  onLoad() {
    // 重新加载页面数据 data 为 true ,触发方式 uni.$emit('reload',true)
    uni.$on('reload', (data) => {
      if (data) {
        this.initData()
      }
    })
    // this.initData();
  },
  onShow() {
    this.initData()
  },
  onPullDownRefresh() {
    this.initData()
  },
  onReachBottom() {
    this.pageNum++
    this.getList()
  },
  methods: {
    filterSubmit(val) {
      this.pageNum = 1
      this.total = null
      this.searchParams = {}
      const { workProgress, deptId, areaId, directorId } = val
      this.searchParams.workProgress = workProgress
      this.searchParams.deptId = deptId
      this.searchParams.areaId = areaId
      this.searchParams.directorId = directorId
      this.getList()
    },
    initData() {
      this.listData = []
      this.isFinished = false
      this.pageNum = 1
      this.pageSize = 10
      this.total = null
      this.getList()
    },
    getList() {
      if (this.isFinished) {
        return
      }
      const data = {
        pageSize: 10,
        pageNum: this.pageNum,
        ...this.searchParams
      }
      if (!this.total || this.total > this.listData.length) {
        getTicketApplyList(data)
          .then((res) => {
            if (this.pageNum === 1) {
              this.listData = res.rows
            } else {
              this.listData.push(...res.rows)
            }
            this.total = res.total
          })
          .finally(() => {
            uni.stopPullDownRefresh()
          })
      }
    },

    applyFor({ projectInfoId, directorFlag, ticketLevelStatus, projectId }) {
      let url = `/pages/jobSlip/work-ticket/apply-for?projectId=${projectId}&projectInfoId=${projectInfoId}&directorFlag=${directorFlag}&ticketLevelStatus=${ticketLevelStatus}`
      const _this = this
      uni.navigateTo({
        url,
        events: {
          reloadEvent: function (isReload) {
            if (isReload) {
              _this.initData()
            }
          }
        }
      })
    },

    detail({ projectInfoId, directorFlag, projectId }) {
      let url = `/pages/jobSlip/work-ticket/apply-for?projectId=${projectId}&projectInfoId=${projectInfoId}&directorFlag=${directorFlag}`
      const _this = this
      uni.navigateTo({
        url,
        events: {
          reloadEvent: function (isReload) {
            if (isReload) {
              _this.initData()
            }
          }
        }
      })
    },
    // 转办
    async transferSelectorChange(obj) {
      let toAssignee = null
      let toAssigneeName = null
      if (Array.isArray(obj)) {
        toAssignee = obj.reduce((acc, cur) => (acc = acc.concat(cur.userId)), []).join(',')
        toAssigneeName = obj.reduce((acc, cur) => (acc = acc.concat(cur.name)), []).join(',')
      } else {
        toAssignee = obj.value
        toAssigneeName = obj.name
      }

      this.transferForm.toAssignee = toAssignee
      this.$modal.confirm(`确定将任务转给【${toAssigneeName}】吗？`).then(() => {
        turnDo(this.transferForm).then(() => {
          this.$modal.showToast('转办成功')
          this.initData()
        })
      })
    },
    // 是否能更换监护人、更换项目负责人
    // 当前登录人必须是项目负责人、项目状态不能是已完成状态
    isChangeUser(item) {
      return item.workProgress !== '3' && item.directorId === store.getters.staffId
    },
    onDeptUserChange(item) {
      let own = this.type === 1 ? '监护人' : '项目负责人'
      if (!item || !item.length) {
        this.$modal.showToast(`请选择${own}`)
        return
      }
      const { name, userId } = item[0]
      this.dataParam.newUserId = userId
      this.dataParam.staffName = name

      this.$modal.confirm(`确定将项目【${this.pName}】的${own}由【${this.curUser}】更换到【${name}】吗？`).then(() => {
        this.changeUser(this.dataParam, own)
      })
    },
    showUserSelect(row, type) {
      this.type = type
      this.pName = row.projectName
      this.curUser = type === 1 ? row.guardianName : row.directorName
      this.dataParam.projectId = row.projectId

      this.deptUserSelectProps = {
        userRequestApi: null,
        withCount: true
      }

      if (this.type === 1) {
        this.dataParam.oldUserId = row.guardianId
        this.deptUserSelectProps = {
          userRequestApi: queryProjectGuardian,
          withCount: false
        }
      } else if (this.type === 2) {
        this.dataParam.oldUserId = row.directorId
      }
      this.$refs.deptUserSelectRef.open()
    },

    changeUser(data, own) {
      let api = ['', changeGuardian, changeProjectDuty]
      api[Number(this.type)](data).then((res) => {
        this.$modal.showToast(`更换${own}成功`)
        this.initData()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.grid-body {
  background-color: transparent;
}

.grid-common {
  margin-bottom: 30rpx;
  background-color: #fff;
  border-radius: 20rpx;
}

.items-center {
  align-items: center;
}

.info-btn {
  flex-shrink: 0;
  margin-right: 0px;
  margin-left: 10px;
}

.check {
  position: relative;

  .title {
    font-size: 34rpx;
    font-weight: 700;
  }

  .icon-style {
    width: 52rpx;
    height: 52rpx;
    margin-right: 20rpx;
  }

  .text {
    color: #999;

    .text-label {
      display: flex;
      word-break: keep-all;
      color: #999;
      max-width: 35%;
    }

    text {
      color: #333;
      display: inline-block;
      word-break: break-all;
    }
  }

  .flex-text {
    padding-top: 24rpx;
    display: flex;
    color: #999;

    text {
      color: #333;
      display: inline-block;
    }
  }

  .bor-top {
    padding-top: 20rpx;
    border-top: 1rpx solid #d5d7e3;
  }
}

.button-wrap-todo {
  align-items: center;
  justify-content: space-between;
  width: 100%;

  .button-wrap-left {
    display: flex;
    align-items: center;

    > view {
      margin-right: 16rpx;
      margin-left: 0;
    }
  }
}

.affix {
  //width: 90px;
  height: 30px;
  position: absolute;
  top: 0;
  right: 0;
}

uni-image.affix-icon {
  height: 30px !important;
  width: 78px !important;
}

.button-wrap {
  .status-button {
    border: 1rpx solid #88b4c4;
    color: #88b4c4;

    &.active {
      border: 1rpx solid #c87c32;
      color: #c87c32;
    }
  }
}

.cu-card-wrap {
  margin-bottom: 24rpx;
  position: relative;

  .title {
    font-size: 34rpx;
    font-weight: 700;
    align-items: center;
    height: 45px;
    margin-top: -15px;
  }

  .icon-style {
    width: 52rpx;
    height: 52rpx;
    margin-right: 20rpx;
  }

  &:first-child {
    margin-top: 24rpx;
  }
}
</style>
